﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace LDDataDownTest
{
    public class TcpClientMana
    {
        public Socket tcpClient;
        public string numstr;
        public bool flag;
    }

    public class CClient
    {
        /// <summary>
        /// 当前电脑的IP
        /// </summary>
        static public string hostIp = "127.0.0.1";
        /// <summary>
        /// 线程管理
        /// </summary>
        static public Dictionary<string,Thread> _threadMana = new Dictionary<string, Thread>();

        static public object sendlock = new object();

        //static public List<TcpClientMana> _tcMana = new List<TcpClientMana>();
        /// <summary>
        /// DIO索引
        /// </summary>
        static Dictionary<string, int> DIOindex = new Dictionary<string, int>();

        #region 获取当前电脑IP
        /// <summary>
        /// 获取当前电脑IP
        /// </summary>
        static public void GetCurrentComputerIP()
        {
            //获取当前电脑IP
            IPHostEntry hostEntry = Dns.GetHostEntry("");
            foreach (IPAddress address in hostEntry.AddressList)
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    hostIp = address.ToString();
                    break;
                }
            }
        }
        #endregion

        /// <summary>
        /// 连接服务器
        /// </summary>
        static public void LinkServer()
        {
            int threadNum = 1;

            Console.WriteLine("请输入要模拟的设备数量，直接回车即默认为1：");
            string num = Console.ReadLine();
            threadNum = num==""?1: Convert.ToInt32(num);

            Console.WriteLine("请输入服务器的IP地址，如果用192.168.1.233地址直接回车即可：");
            string ip = Console.ReadLine();
            if(ip!="")
            {
                hostIp = ip;
            }
            else
            {
                hostIp = "192.168.1.233";
            }

            Console.WriteLine("将要创建的线程数为:" + (threadNum*2).ToString());
            Console.WriteLine("服务器IP为："+ hostIp);

            for(int i=0;i< threadNum; i++)
            //int i = 1;
            {
                //定义一个套接字监听  
                Socket socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //获取文本框中的IP地址  
                IPAddress address = IPAddress.Parse( hostIp);

                //将获取的IP地址和端口号绑定在网络节点上  
                IPEndPoint point = new IPEndPoint(address, 65431);

                try
                {
                    socketclient.Connect(point);

                    int DIOStatus = 0;
                    DIOindex.Add(socketclient.LocalEndPoint.ToString(), DIOStatus);

                    TcpClientMana tcm = new TcpClientMana();
                    tcm.flag = false;
                    Thread th = new Thread(TCPClientThreadSendNew );
                    tcm.tcpClient = socketclient;
                    tcm.numstr = i.ToString();
                    _threadMana.Add(tcm.numstr, th);
                    th.IsBackground = true;
                    th.Start(tcm);
                    

                    Console.WriteLine("已创建的线程数为：" + (2*i+1).ToString());

                    Thread thr = new Thread(TCPClientThreadNew);
                    thr.IsBackground = true;
                    thr.Start(tcm);
                    Console.WriteLine("已创建的线程数为：" + (2 * (i + 1)).ToString());
                }
                catch {
                    Console.WriteLine("连接失败。。。");
                }

                //Thread.Sleep(100);
            }
        }

        /// <summary>
        /// TCP客户端线程
        /// </summary>
        /// <param name="clientObj"></param>
        /// <param name="numObj"></param>
        static public void TCPClientThreadNew(object clientObj)
        {
            TcpClientMana tcm = clientObj as TcpClientMana;
            Socket tcpClient = tcm.tcpClient;
            string numstr = tcm.numstr;
            byte[] buffer = new byte[8192];
            int dataLen = 0;
            int bmdIndex = 0;
            int machineNum = 0;

            Send_73(0, tcm.tcpClient);

            while (true)
            {
                try
                {
                    dataLen = tcpClient.Receive(buffer);

                    string cmd = Encoding.UTF8.GetString(buffer, 0, 3);

                    switch(cmd)
                    {
                        case "#73":
                            bmdIndex = Convert.ToInt32( Encoding.UTF8.GetString(buffer, 7, 8),16);
                            Send_73(bmdIndex, tcm.tcpClient);
                            break;

                        case "#06":
                            bmdIndex = Convert.ToInt32(Encoding.UTF8.GetString(buffer, 18, 8), 16);
                            break;

                        case "#0A":
                            machineNum = Convert.ToInt32(Encoding.UTF8.GetString(buffer, 3, 4), 16);
                            
                            //tcpClient.Send()
                            break;
                    }


                    Encoding.UTF8.GetString(buffer, 3, 4);

                    string rATCmd = MyConvert.AsciiByteToString(buffer, dataLen);
                    Console.WriteLine("接收：" + rATCmd);

                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    _threadMana.Remove(tcm.numstr);
                    tcm.tcpClient.Close();
                    Thread.CurrentThread.Abort();

                }
            }
        }

        static private void Send_73(int bmdIndex,Socket sk)
        {

            //sk.Send()
        }

        static public void TCPClientThreadSendNew(object clientObj)
        {
            TcpClientMana tcm = clientObj as TcpClientMana;
            Socket tcpClient = tcm.tcpClient;
            
            string cmdStr = "";

            while (true)
            {
                try
                {
                    cmdStr = "Device Number:" + (tcm.numstr + 1).ToString();
                    byte[] buf = MyConvert.StringToAsciiByte(cmdStr);
                    tcpClient.Send(buf);
                    tcm.flag = true;

                    Thread.Sleep(500);
                }
                catch
                {

                }
            }
        }
    }
}
